package com.young.modbus.config;

import com.serotonin.modbus4j.ModbusFactory;
import com.serotonin.modbus4j.ModbusMaster;
import com.serotonin.modbus4j.ip.IpParameters;
import com.serotonin.modbus4j.ip.tcp.TcpMaster;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @Author: Young
 * @CreateTime: 2024-12-30
 * @Description:
 * @Version: 1.0
 */
@Slf4j
@Configuration
public class ModbusConfig {

    @Autowired
    private PlcConfig config;

    private static ModbusFactory modbusFactory;

    static {
        modbusFactory = new ModbusFactory();
    }

    @Bean
    public ModbusMaster modbusMaster() {
        IpParameters params = new IpParameters();
        params.setHost(config.getHost());
        params.setPort(config.getPort());
        params.setEncapsulated(false);
        ModbusMaster master = new TcpMaster(params, true);
        master.setTimeout(config.getTimeout());
        master.setRetries(config.getRetries());
        try {
            master.init();
            log.info("plc初始化连接成功！");
        } catch (Exception e) {
            log.error("plc初始化连接失败，{}", e.getMessage());
        }
        return master;
    }
}
